package net.uman.web.manager;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.uman.entity.User;
import net.uman.framework.modules.orm.Page;
import net.uman.framework.modules.orm.PropertyFilter;
import net.uman.framework.modules.security.springsecurity.SpringSecurityUtils;
import net.uman.framework.modules.web.struts2.Struts2Utils;
import net.uman.service.UserManager;
import net.uman.util.Constants;
import net.uman.web.CrudActionSupport;

import org.apache.struts2.convention.annotation.Namespace;
import org.hibernate.tool.hbm2x.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
@Namespace("/manager")
public class AccountAction extends CrudActionSupport<User> {
	private static final long serialVersionUID = -6859411297210213983L;
	
	public int searchUserType = Constants.USER_TYPE_ADMIN;
	public String searchUserTypeName;
	public Long userId;
	public Integer userType;
	
	@Autowired
	private UserManager userManager;

	//列表
	@Override
	public String list() throws Exception {
		if(searchUserType == Constants.USER_TYPE_ADMIN){
			searchUserTypeName ="管理员列表";
		}else if(searchUserType == Constants.USER_TYPE_OPERATOR){
			searchUserTypeName="操作员列表";
		}else if(searchUserType == Constants.USER_TYPE_USER){
			searchUserTypeName="会员列表";
		}else if(searchUserType == Constants.USER_TYPE_PLATER){
			searchUserTypeName="版主列表";
		}
		return "userlist";
	}
	//跳转到 添加用户 界面
	public String add(){
		return "adduser";
	}
	
	public void adminUserData(){
		String typeString = String.valueOf(Constants.USER_TYPE_ADMIN);
		getJsonData(typeString);
	}
	
	public void operatorUserData(){
		String typeString = String.valueOf(Constants.USER_TYPE_OPERATOR);
		getJsonData(typeString);
	}
	
	public void commonUserData(){
		String typeString = String.valueOf(Constants.USER_TYPE_USER);
		getJsonData(typeString);
	}
	
	public void platerUserData(){
		String typeString = String.valueOf(Constants.USER_TYPE_PLATER);
		getJsonData(typeString);
	}

	private void getJsonData(String typeString) {
		JSONObject jsonobject = new JSONObject();
		JSONArray jsonArray = new JSONArray();
		Page<User> page = getUserPage(typeString);
		for(User user : page.getResult()){
			JSONObject json = new JSONObject();
			json.put("id", user.getId());
			json.put("userName", user.getName());
			json.put("email", user.getEmail());
			json.put("phone", user.getPhone());
			json.put("photoUrl", user.getPhotoUrl());
			json.put("point", user.getPoint());
			jsonArray.add(json);
		}
		jsonobject.put("rows", jsonArray);
		jsonobject.put("total", page.getTotalCount());
		Struts2Utils.renderJson(jsonobject);
	}

	private Page<User> getUserPage(String typeString) {
		List<PropertyFilter> filters = new ArrayList<PropertyFilter>();
		filters.add(new PropertyFilter("filter_EQI_type", typeString));
		Page<User> page = new Page<User>(10);
		page.setPageNo(pageNum);
		page = userManager.getUserPage(page,filters);
		return page;
	}
	//删除用户
	public void deleteUser(){
		if(userId!=null){
			userManager.delete(userId);
		}
	}
	
	public void userDetail(){
		if(userId!=null){
			user = userManager.getUser(userId);
		}
	}
	
	public void modPwd(){
		String pwd_old = Struts2Utils.getParameter("pwd_old");
		String pwd_new = Struts2Utils.getParameter("pwd_new");
		if(!StringUtils.isEmpty(pwd_old)&&!StringUtils.isEmpty(pwd_new)&&userId!=null){
			user = userManager.getUser(userId);
			if(user.getPassword()!=new Md5PasswordEncoder().encodePassword(pwd_old, user.getLoginName())){
				Struts2Utils.renderText("原始密码错误！");
			}else{
				pwd_new = new Md5PasswordEncoder().encodePassword(pwd_new, user.getLoginName());
				user.setPassword(pwd_new);
				userManager.save(user);
				Struts2Utils.renderText("密码设置完成！");
			}
		}
	}
	
	public void addUser(){
		try{
			User newuser = new User();
			newuser.setLoginName(Struts2Utils.getParameter("loginName"));
			newuser.setName(Struts2Utils.getParameter("userName"));
			User e_user = userManager.getUserByLoginName(newuser.getLoginName());
			newuser.setAddDate(new Date(System.currentTimeMillis()));
			newuser.setEmail(Struts2Utils.getParameter("email"));
			if(e_user==null){
				String pwd = Struts2Utils.getParameter("password");
				newuser.setPassword(new Md5PasswordEncoder().encodePassword(pwd, newuser.getLoginName()));
				newuser.setPhone(Struts2Utils.getParameter("phone")!=null?Struts2Utils.getParameter("phone"):"");
				newuser.setPhotoUrl(Struts2Utils.getParameter("photoUrl")!=null?Struts2Utils.getParameter("photoUrl"):"");
				newuser.setPoint(0);
				newuser.setType(Integer.parseInt(Struts2Utils.getParameter("role")));
				userManager.save(newuser);
				Struts2Utils.renderText("注册用户完成！");
			}else{
				Struts2Utils.renderText("用户名或登录名已存在！");
			}
		}catch (Exception e) {
			e.printStackTrace();
			Struts2Utils.renderText("注册用户失败！");
		}
	}
	
	public void checkUser(){
		try {
			Struts2Utils.getSession().removeAttribute("user");
			String userName = Struts2Utils.getParameter("username");
			String password = Struts2Utils.getParameter("password");
			User user_ck = userManager.getUserByLoginName(userName);
			if(user_ck != null){
				if(user_ck.encodePassword(password).equals(user_ck.getPassword())){
					Struts2Utils.setSessionAttribute("user", user_ck);
					Struts2Utils.renderText("success");
				}else{
					Struts2Utils.renderText("密码错误！");
				}
			}else{
				Struts2Utils.renderText("用户名不存在！");
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	
	public String showUserInfo(){
		user = SpringSecurityUtils.getCurrentUser();
		userType = user.getType();
		if(userType == Constants.USER_TYPE_ADMIN){
			return "showAdminInfo";
		}else if(userType == Constants.USER_TYPE_OPERATOR){
			return "showOperatorInfo";
		}else if(userType == Constants.USER_TYPE_PLATER){
			return "showPlaterInfo";
		}else{
			return ERROR;
		}	
	}
	
	public String updateUser() throws Exception{
		user = SpringSecurityUtils.getCurrentUser();
		return "userupdate";
	}
	
	@Override
	public String input() throws Exception {
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String delete() throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected void prepareModel() throws Exception {
//		if(userId != null){
//			user = userManager.getUser(userId);
//		}else{
//			user = SpringSecurityUtils.getCurrentUser();
//		}
	}
	public User getModel() {
		// TODO Auto-generated method stub
		return null;
	}
}
